package ar.utn.jess.common;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;


public class JsonUtil {

	
	public static Map<String, Object> getAsMap(String json) {
		Map<String, Object> result = new HashMap<String, Object>();

		JsonParser parser = new JsonParser();
		JsonElement element = parser.parse(json);
		Set<Map.Entry<String, JsonElement>> elements = element.getAsJsonObject().entrySet();
		
		for (Map.Entry<String, JsonElement> entry : elements) {
			String key = entry.getKey();
	        JsonElement value = entry.getValue();
	        
	        
	        if (value.isJsonArray()) {
	        	JsonArray jsonArray = value.getAsJsonArray();	        	
	        	Object[] array = new Object[jsonArray.size()];
	        	for(int i = 0; i < array.length; i++) {
	        		array[i] = getAsMap(jsonArray.get(i).toString());	        		
	        	}
	        	result.put(key, array);
	        }
	        else if(value.isJsonPrimitive()){
	        	JsonPrimitive primitive = value.getAsJsonPrimitive();
	        	
	        	if(primitive.isString())
	        		result.put(key, value.getAsString());
	        	else if(primitive.isBoolean())
	        		result.put(key, value.getAsBoolean());
	        	else if(primitive.isNumber())
	        		result.put(key, value.getAsBigDecimal());
	        }
		}

		
		return result;
	}
}
